package dbops

import (
	"GoStreamVideoWebsite/api/defs"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/spf13/viper"
	"os"
	"sync"
)

var (
	dbConn *gorm.DB
	err    error
	lock   sync.RWMutex
)

//从配置文件读取配置
func init() {
	workDir, _ := os.Getwd()
	viper.SetConfigName("application")
	viper.SetConfigType("yml")
	viper.AddConfigPath(workDir + "/api/dbops")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
}
func init() {
	driverName := viper.GetString("datasource.driverName")
	host := viper.GetString("datasource.host")
	port := viper.GetString("datasource.port")
	database := viper.GetString("datasource.database")
	username := viper.GetString("datasource.username")
	password := viper.GetString("datasource.password")
	charset := viper.GetString("datasource.charset")
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local",
		username,
		password,
		host,
		port,
		database,
		charset)
	db, err := gorm.Open(driverName, args)
	if err != nil {
		panic("failed to connect database err: " + err.Error())
	}
	db.AutoMigrate(&defs.Users{})
	db.AutoMigrate(&defs.Video_Info{})
	db.AutoMigrate(&defs.Comments{})
	db.AutoMigrate(&defs.Sessions{})
	dbConn = db
}
